import 'package:flutter/material.dart';
import 'package:flutter_stort/model/cart_entity.dart';
import 'package:flutter_stort/model/goods_entity.dart';
import 'package:flutter_stort/utils/event_bus.dart';
import 'package:flutter_stort/widget/cart_add_num.dart';
import 'package:flutter_stort/widget/load_image.dart';
import 'package:flutter_stort/widget/load_state_view.dart';

class ShoppingCartPage extends StatefulWidget {
  @override
  _ShoppingCartPageState createState() => _ShoppingCartPageState();
}

class _ShoppingCartPageState extends State<ShoppingCartPage> {
  ScrollController scrollController = ScrollController();
  LoadState _loadState = LoadState.LOADING;
  bool _selectAll = true;

  double _allPrice = 0.0;
  List<CartEntity> _listData = [];

  @override
  void initState() {
    EventBusUtils.eventBus.on<String>().listen((value) {
      if (value.isNotEmpty && value == "add") {
        this.setState(() {
          _listData.add(CartEntity(
            isSelect: true,
            num: 1,
            good: GoodsEntity(
              title: "小米洗烘一体机",
              id: "1",
              url:
                  "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2699161186,1318363053&fm=26&gp=0.jpg",
              createTime: "2019-10-10 00:00",
              content: "智能烘干，高效净衣，省水省电",
              price: 1999.00,
              stock: 200,
              freight: "免费",
            ),
          ));
          _reshSelectData();
          _loadState = LoadState.SUCCESS;
        });
      }
    });
    _getCartData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "购物车",
          style: TextStyle(
            fontSize: 20,
          ),
        ),
      ),
      body: Container(
        child: Column(
          children: [
            Expanded(
              flex: 1,
              child: LoadStateView(
                loadState: _loadState,
                successWidget: ListView.builder(
                  itemBuilder: _cartItemBuild,
                  itemCount: _listData.length,
                ),
                erroRetry: () {},
              ),
            ),
            Container(
              height: 50,
              color: Colors.white,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    flex: 1,
                    child: Row(
                      children: [
                        Checkbox(
                          activeColor: Colors.pink,
                          value: _selectAll,
                          onChanged: (isSelect) {
                            setState(() {
                              if(_listData.length>0){
                                _selectAll = isSelect;
                                for(int i=0;i<_listData.length;i++){
                                  _listData[i].isSelect= isSelect;
                                }
                                _getAllPrice();
                              }else{
                                _selectAll = false;
                              }
                            });
                          },
                        ),
                        Text(
                          "全选",
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 16,
                          ),
                        ),
                        Text(
                          "￥$_allPrice 元 ",
                          textAlign: TextAlign.right,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: Colors.red,
                            fontSize: 16,
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    width: 100,
                    height: 50,
                    child: RaisedButton(
                      color: Colors.red,
                      onPressed: _submitPrice,
                      child: Text(
                        "结算",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///提交结算
  void _submitPrice() {
    print("总金额 $_allPrice");
  }

  ///刷新选择项
  void _reshSelectData() {
    int selectNum = 0;
    setState(() {
      if (_listData.length == 0) {
        _selectAll = false;
      } else {
        for (var i = 0; i < _listData.length; i++) {
          if (_listData[i].isSelect) {
            selectNum++;
          }
        }
        if (selectNum == _listData.length) {
          _selectAll = true;
        } else {
          _selectAll = false;
        }
      }
      _getAllPrice();
    });
  }

  ///获取所有数据
  void _getAllPrice() {
    _allPrice = 0;
    for (var i = 0; i < _listData.length; i++) {
      if (_listData[i].isSelect) {
        _allPrice += (_listData[i].good.price * _listData[i].num);
      }
    }
  }

  ///添加数据
  void _getCartData() {
    setState(() {
      if (_listData.isNotEmpty && _listData.length > 0) {
        _loadState = LoadState.SUCCESS;
      } else {
        _loadState = LoadState.EMPTY;
      }
      _reshSelectData();
    });
  }

  ///获取购物车
  Widget _cartItemBuild(BuildContext context, int position) {
    return Container(
      padding: EdgeInsets.only(top: 6,bottom: 6,),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Checkbox(
            activeColor: Colors.pink,
            value: _listData[position].isSelect,
            onChanged: (isSelect) {
              setState(() {
                _listData[position].isSelect = isSelect;
                _reshSelectData();
              });
            },
          ),
          LoadImageView(
            width: 90,
            height: 90,
            fit: BoxFit.cover,
            imageUrl: _listData[position].good.url,
          ),
          SizedBox(width: 4),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                _listData[position].good.title,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 16,
                ),
              ),
              SizedBox(height: 6),
              Text(
                _listData[position].good.content,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
              ),
              SizedBox(height: 6),
              Text(
                "￥ ${_listData[position].good.price}",
                style: TextStyle(
                  color: Colors.red,
                  fontSize: 14,
                ),
              ),
              SizedBox(height: 6),
              CartNumView(
                num: _listData[position].num,
                showCartNum: (num) {
                  print("  $num  ");
                  setState(() {
                    _listData[position].num = num;
                    _getAllPrice();
                  });
                },
              ),
            ],
          ),
        ],
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            color: Colors.grey,
            width: 0.5,
            style: BorderStyle.solid,
          ),
        ),
      ),
    );
  }
}
